package com.mobilekites.service;

import java.io.IOException;

import org.json.JSONObject;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.mobilekites.MobileKitesApp;
import com.mobilekites.api.DfeApi;
import com.mobilekites.util.KitesLog;
import com.mobilekites.util.KitesPrefers;
import com.mobilekites.util.Utility;

public class KitesGCMService extends IntentService {
	private GoogleCloudMessaging mGCM;
	private final static String SENDER_ID = MobileKitesApp.get().getKitesConfig().getGCMSenderId();
	private final static String EXTRA_ACTION = "gcm_service_action";
	private final static int ACTION_REGISTER_GCM = 100;

	public KitesGCMService() {
		super("KitesGCMService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		if (intent == null)
			return;
		int action = intent.getIntExtra(EXTRA_ACTION, Integer.MIN_VALUE);
		if (action == ACTION_REGISTER_GCM) {
			registerGCM();
		}
	}

	public static void startRegisterGCM(Context context) {
		Intent intent = new Intent(context, KitesGCMService.class);
		intent.putExtra(EXTRA_ACTION, ACTION_REGISTER_GCM);
		context.startService(intent);
	}

	private void registerGCM() {
		mGCM = GoogleCloudMessaging.getInstance(getApplicationContext());
		try {
			final String regId = mGCM.register(SENDER_ID);
			KitesLog.i(String.format("RegistrationId=%s", regId));
			DfeApi dfeApi = MobileKitesApp.get().getDfeApi();
			dfeApi.registerAndroid(
					Utility.getDeviceId(getApplicationContext()), regId,
					new Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							KitesLog.i(String
									.format("Send regId to Kites success, with response=%s",
											response.toString()));
							KitesPrefers preferences = MobileKitesApp.get()
									.getKitesPrefers();
							preferences.storeRegistrationIdGCM(regId);
							preferences.storeRegistrationIdVersion(Utility
									.getAppVersion(getApplicationContext()));
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							KitesLog.e(String
									.format("Send regId to Kites failure, with response=%s",
											error.getMessage()));
						}
					});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
